//
//  WXEmotionItemCell.swift
//  weibo
//
//  Created by 王旭 on 16/4/28.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit

class WXEmotionItemCell: UICollectionViewCell {
    
    //存放数据的数组
    var emotions : [WXEmotionModel]? {
        didSet{
            //隐藏所有按钮,解决cell复用问题
            for value in emotionButtons {
                value.hidden = true
            }
            //判断数据是否存在
            guard let e = emotions else{
                return
            }
            //给表情按钮赋值
            for (index,emotion) in e.enumerate() {
                //显示按钮
                let button = emotionButtons[index]
                button.hidden = false
                
                button.emotion = emotion
//--------------------以下为代码抽取到WXEmotionButton-----------------
                //                if emotion.type == "1" {
                //                    button.setImage(nil, forState: .Normal)
                //                    button.setTitle((emotion.code! as NSString).emoji(), forState: .Normal)
                //                }else{
                //                    //设置图片
                //                    let image = UIImage(named: "\(emotion.folderName ?? "")/\(emotion.png ?? "")", inBundle: WXEmotionViewModel.sharedEmotionViewModel.emotionBundel, compatibleWithTraitCollection: nil)
                ////                    print("\(emotion.folderName ?? "")/\(emotion.png ?? "")")
                //                    button.setImage(image, forState: .Normal)
                //                    button.setTitle(nil, forState: .Normal)
                //                }
//--------------------以上为代码抽取到WXEmotionButton-----------------
            }
        }
    }
    
    //测试用
    var indexPath: NSIndexPath? {
        didSet{
//            testLabel.text = "第\(indexPath?.section ?? 0)组，第\(indexPath?.item ?? 0)页"
            testLabel.hidden = indexPath?.section != 0
        }
    }
    
    //表情按钮数组
    var emotionButtons : [WXEmotionButton] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        //测试标签
       contentView.addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        
        //添加表情按钮数组
        addChildButtons()
        
        //给contentView添加长按的手势
        let longPressGR = UILongPressGestureRecognizer(target: self, action: "responseGToLongPress:")
        //--------------------以下为测试代码-----------------
        // 最短的触发时间
        // longPress.minimumPressDuration = 5
        //--------------------以上为测试代码-----------------
        contentView.addGestureRecognizer(longPressGR)

        
        //添加删除按钮
        contentView.addSubview(deleteButton)
        
//--------------------设置删除按钮位置法二-----------------
//        let buttonW = self.frame.width / CGFloat(EmotionKeyboardCol)
//        let buttonH = self.frame.height / CGFloat(EmotionKeyboardRow)
//        deleteButton.snp_makeConstraints { (make) -> Void in
//            make.centerY.equalTo(self.contentView.snp_bottom).offset(-buttonH / 2)
//            make.centerX.equalTo(self.contentView.snp_trailing).offset(-buttonW / 2)
//        }
//--------------------设置删除按钮位置法二-----------------
        
    }
    
    //添加表情按钮
    private func addChildButtons() {
        //添加表情按钮数组
        //按钮个数
        let count = EmotionKeyboardCount
        for _ in 0..<count {
            let button = WXEmotionButton()
            //--------------------以下为测试代码-----------------
            //            //测试用:背景色
            //            button.backgroundColor = RandomColor
            //--------------------以上为测试代码-----------------
            //点击事件
            button.addTarget(self, action: "emotionButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //字体大小
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            contentView.addSubview(button)
            emotionButtons.append(button)
        }
    }
    
    @objc private func responseGToLongPress(gesture: UILongPressGestureRecognizer){
        
        
        // 1. 取到手指所在的位置
        let location = gesture.locationInView(gesture.view)
        //--------------------以下为测试代码-----------------
        //        print(location)
        //--------------------以上为测试代码-----------------
        
        // 2. 找到该位置所对应的按钮
        func buttonWithLocation(location: CGPoint) -> WXEmotionButton? {
            for value in emotionButtons {
                //if value的范围是否包含传入的点，如果包含，直接返回value
                if CGRectContainsPoint(value.frame, location) {
                    return value
                }
            }
            return nil
        }
        
        // 通过点找到点对应的表情按钮
        guard let button = buttonWithLocation(location) else {
            popView.removeFromSuperview()
            return
        }
        
        switch gesture.state {
        case .Began,.Changed:
            if popView.emotionPopButton.emotion == button.emotion {
                return
            }
            // 0. 取到最上层的window
            let window = UIApplication.sharedApplication().windows.last!
            // 2.1 坐标转换：将按钮在contentView里面的坐标值转换到window上面
            let rect = button.superview!.convertRect(button.frame, toView: window)
            // 中心点一样
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 给 PopView里面的按钮赋值
            popView.emotionPopButton.emotion = button.emotion
            // 3. 添加
            window.addSubview(popView)
        default:
            popView.emotionPopButton.emotion = nil
            popView.removeFromSuperview()
        }

    }
    
    //删除按钮点击事件
    @objc private func deleteButtonClick() {
        NSNotificationCenter.defaultCenter().postNotificationName(WXEmoticonDeleteButtonClickNotification, object: nil)
    }
    
    //表情按钮点击事件
    @objc private func emotionButtonClick(button:WXEmotionButton) {
        print(button.emotion?.chs)
        // 保存最近表情
    WXEmotionViewModel.sharedEmotionViewModel.saveRecentEmoticon(button.emotion!)
        //发通知
        NSNotificationCenter.defaultCenter().postNotificationName(WXEmoticonButtonClickNotification, object: nil, userInfo: ["emoticon": button.emotion!])
        //1.获得窗口
        let window = UIApplication.sharedApplication().windows.last!
        //2.初始化view
        let popView = WXEmotionPopView.popView()
        //3.获得位置
        let rect = button.superview!.convertRect(button.frame, toView: window)
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        //给popView按钮赋值
        popView.emotionPopButton.emotion = button.emotion
        //4.添加
        window.addSubview(popView)
        //5.移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置表情按钮的位置和大小
        //大小
       let buttonW = self.frame.width / CGFloat(EmotionKeyboardCol)
       let buttonH = (self.frame.height - 25) / CGFloat(EmotionKeyboardRow)
        //位置
        for (index,value) in emotionButtons.enumerate() {
            //计算行列
            let row = index / EmotionKeyboardCol
            let col = index % EmotionKeyboardCol
            let buttonX = CGFloat(col) * buttonW
            let buttonY = CGFloat(row) * buttonH
            value.frame = CGRect(x: buttonX, y: buttonY, width: buttonW, height: buttonH)
        }
        
        // 设置删除按钮的位置
        let deleteButtonX = self.frame.width - buttonW
        let deleteButtonY = self.frame.height - buttonH - 25
        
        deleteButton.frame = CGRect(x: deleteButtonX, y: deleteButtonY, width: buttonW, height: buttonH)
    }
    
    //懒加载标签
    private lazy var testLabel :UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()
    
    //懒加载删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        return button
    }()
    
    //懒加载长按手势popView
    private lazy var popView: WXEmotionPopView = {
        let popView = WXEmotionPopView.popView()
        return popView
    }()

}